/*
 * @Author:
 * @Date: 2022-11-24 13:56:00
 * @LastEditors:
 * @LastEditTime: 2022-12-23 17:55:33
 * @FilePath: \immoka-admin\src\utils\ossProvider.js
 * @Description:
 *
 * Copyright (c) 2022 by  , All Rights Reserved.
 */
import { ossSts } from '@/api/common'
import { Message } from 'element-ui'

import sha1 from 'sha1-file-web'
import OSS from 'ali-oss'

class OssProvider {
  __ossIns = null

  async getOssIns() {
    // debugger
    if (this.__ossIns) return this.__ossIns
    const ossData = await this.getEffectiveIns()
    if (ossData) {
      const { region, accessKeyId, accessKeySecret, bucket, securityToken } = ossData

      this.__ossIns = new OSS({
        region,
        accessKeyId,
        accessKeySecret,
        bucket,
        stsToken: securityToken,
        refreshSTSToken: this.getEffectiveIns,
        refreshSTSTokenInterval: 1e3 * 60 * 5,
        secure: true
      })
    } else {
      throw ReferenceError('无法正确获取oss对象引用！')
    }
    return this.__ossIns
  }

  async getEffectiveIns() {
    try {
      const {
        data: { region, accessKeyId, accessKeySecret, securityToken, bucket, baseUrl }
      } = await ossSts()
      return {
        accessKeyId,
        accessKeySecret,
        securityToken,
        region,
        bucket,
        baseUrl
      }
    } catch (e) {
      return void Message.error('获取 oss 信息失败~')
    }
  }

  async upload(file, dir) {
    const OSSIns = await this.getOssIns()
    /* 处理文件路径 */
    const extensionName = file.name.split('.').reverse()[0]
    const fileName = await sha1(file)
    const filePath = `${dir}/${fileName}.${extensionName}`

    const { bucket, region } = OSSIns.options
    const prefix = `https://${bucket}.${region}.aliyuncs.com/`
    const remotePath = `${prefix}${filePath}`
    try {
      // const { status } = await fetch(remotePath, { method: 'head', mode: 'no-cors' })

      // if (status === 200) return Promise.resolve(remotePath)

      const result = await OSSIns.put(filePath, file)
      return Promise.resolve(result.url)
    } catch (e) {
      return Promise.reject(e)
    }
  }
}

export default OssProvider
